package com.project.application.framework.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.project.application.common.utils.DateUtils;
import com.project.application.common.utils.SecurityUtils;
import com.project.application.common.utils.ServletUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDateTime;

/**
 * mybatis-plus配置
 *
 * @author levnli
 */
@Configuration
@MapperScan("com.project.application.**.mapper")
public class MybatisPlusConfig {

    private final String registerUrl = "/register";

    /**
     * 相当于顶部的：@MapperScan("com.project.application.**.mapper")
     * {@code @MapperScan("com.project.application.**.mapper")}
     * 这里可以扩展，比如使用配置文件来配置扫描Mapper的路径
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setBasePackage("com.project.application.**.mapper");
        return scannerConfigurer;
    }

    /**
     * 注入插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        // 防止全表删除
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }

    /**
     * 注入公共字段自动填充策略
     */
    @Bean
    public MetaObjectHandler mpMetaObjectHandler() {
        return new MetaObjectHandler() {
            /**
             * 插入元对象字段填充（用于插入时对公共字段的填充）
             *
             * @param metaObject 元对象
             */
            @Override
            public void insertFill(MetaObject metaObject) {
                if (registerUrl.equals(ServletUtils.getRequest().getRequestURI())) {
                    String username = (String) metaObject.getValue("userName");
                    this.setFieldValByName("createBy", username, metaObject);
                    this.setFieldValByName("updateBy", username, metaObject);
                } else {
                    String username = SecurityUtils.getUsername();
                    this.setFieldValByName("createBy", username, metaObject);
                    this.setFieldValByName("updateBy", username, metaObject);
                }
                this.setFieldValByName("createTime", DateUtils.getNowDate(), metaObject);
                this.setFieldValByName("updateTime", DateUtils.getNowDate(), metaObject);
                this.setFieldValByName("delFlag", String.valueOf(0), metaObject);
                this.setFieldValByName("version", 0, metaObject);
            }

            /**
             * 更新元对象字段填充（用于更新时对公共字段的填充）
             *
             * @param metaObject 元对象
             */
            @Override
            public void updateFill(MetaObject metaObject) {
                this.setFieldValByName("updateBy", SecurityUtils.getUsername(), metaObject);
                this.setFieldValByName("updateTime", DateUtils.getNowDate(), metaObject);
            }
        };
    }
}
